package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSON;
import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.model.BaseVerificationCode;
import net.lcheng.model.User;
import net.lcheng.service.BaseVerificationCodeService;
import net.lcheng.service.UserService;
import net.lcheng.service.impl.UserServiceImpl;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.utils.MobileMessageSend;
import net.lcheng.vo.RegisterEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * Created by zwr on 2016/6/28 0028.
 */
@Controller
public class RegController {
    @Autowired
    private UserService userService;
    @Autowired
    private BaseVerificationCodeService baseVerificationCodeService;
    @Autowired
    private UserServiceImpl getUserByPhone;
    /**
     * 注册GET
     */
    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public String Index(Model model) {
        if (!model.containsAttribute("RegisterEntity")) {
            model.addAttribute("RegisterEntity", new RegisterEntity());
        }
        return "reg";
    }
  /** 注册post*/
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public String reg(Model model, @Valid @ModelAttribute("RegisterEntity") RegisterEntity user, BindingResult result, @RequestParam("number") String verifyCode, @RequestParam("userPhone") String userPhone, @RequestParam("number") String number) {
        if (result.hasErrors()) {
            return "reg";
        }
        User userModel = getUserByPhone.getUserByPhone(user.getUserPhone());
        if (userModel != null) {
            result.rejectValue("userPhone", "misFormat", "该手机号码已存在");//这个函数有好几个重载的变体
            model.addAttribute("error", "该手机号码已存在");
            return "reg";
        }
        if (number==null||number.equals("")){
            result.rejectValue("number", "misFormat", "请输入验证码！");
            return "reg";
        }
        /**检验输入的验证码是否过期了*/
        BaseVerificationCode code = baseVerificationCodeService.getByPhoneAndCode(userPhone, verifyCode);
        if (code != null) {
            //验证码过期,刷新修改页面
            if (new Date().after(code.getExpirationTime())) {
                result.rejectValue("number", "misFormat", "验证码过期！");
                return "reg";
            }else {
//                if (user.getPassword().equals(user.getRePassword())) {
//                    result.rejectValue("password", "misFormat", "两次密码不一样！");
//                    return "reg";
//                }
                Subject currentUser = SecurityUtils.getSubject();
                //插入数据库
                User user1 = new User();
                user1.setUserId(UUID.randomUUID().toString());
                user1.setUserPhone(user.getUserPhone());
                user1.setUserPwd(ParseMD5.parseStrToMd5L32(user.getUserPwd()));
                user1.setAccountBalance(BigDecimal.valueOf(0.0));
                user1.setIntegralBalance(0);
                user1.setCommissionBalance(BigDecimal.valueOf(0.0));
                user1.setRegTime(new Date());
                user1.setUserTypeTypeId(1);
                int resultId = userService.insert(user1);

                if (resultId < 0) {
                    model.addAttribute("errorType", 5);
                    model.addAttribute("error", "请重试");
                    return "reg";
                } else {
                    //注册成功,自动登录
                    SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUserPhone(), user.getUserPwd()));
                    return "redirect:/my";
                }
            }
        }else {
            result.rejectValue("number", "misFormat", "验证码错误！");
            return "reg";
        }
    }

    /**
     * 发送验证码
     * @return
     */
    @RequestMapping("/user/register_phone/{userPhone}")
    public @ResponseBody
    int sendingVerificationCodeAjax(@PathVariable("userPhone") String userPhone) throws IOException {
        /**生成验证码，并保存验证码*/
        String verifyCode=baseVerificationCodeService.insert(userPhone,1);
        /**保存成功，就发送验证码*/
        //int sendStatus=MessageUtils.sendMsg(phoneNum,"您的验证码是"+verifyCode+"[有效期10分钟]");
        int sendStatus = MobileMessageSend.sendMsg(userPhone,verifyCode);
        //发送成功返回0
        System.out.println("您的验证码是"+verifyCode);
        return sendStatus;
    }
    /**
     * 判断手机号码
     * @return
     */
    @RequestMapping("/checkPhoneNum")
    @ResponseBody
    public String checkPhoneNum (String phoneNum){
        System.out.println(phoneNum);
        User userModel = getUserByPhone.getUserByPhone(phoneNum);
        if (userModel != null) {
            return "yes";
        }
        return "no";
    }


}
